package com.qf.fmcommodity.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmcommodity.user.entity.Users;
import com.qf.fmcommodity.user.service.IUsersService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    IUsersService iUsersService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {



       return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String username = (String) authenticationToken.getPrincipal();

        Users users = getUserFromDB(username);

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                users,users.getPassword(),
                ByteSource.Util.bytes(users.getSalt()),this.getName()
        );

        return simpleAuthenticationInfo;
    }

    private Users getUserFromDB(String username) {

        QueryWrapper<Users> wrapper = new QueryWrapper<>();

        wrapper.eq("username",username);

        Users one = iUsersService.getOne(wrapper);


        return one;
    }
}
